package com.piotrs10.bsk.gui.views;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.piotrs10.bsk.dao.FakturaDao;
import com.piotrs10.bsk.dao.KlientDao;
import com.piotrs10.bsk.dao.PermissionsDao;
import com.piotrs10.bsk.dao.PracownikDao;
import com.piotrs10.bsk.dao.SalonDao;
import com.piotrs10.bsk.dao.SamochodDao;
import com.piotrs10.bsk.dao.SprzedajeDao;
import com.piotrs10.bsk.dao.SprzedazDao;
import com.piotrs10.bsk.gui.BskGuiApplication;
import com.piotrs10.bsk.model.permissions.SimplePermissionEntry;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ChameleonTheme;

public class MainView extends VerticalLayout implements Command,
		Button.ClickListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8709590024266551789L;

	private final String NAMES[] = new String[] { "Samochod", "Sprzedaz",
			"Klient", "Faktura", "Salon", "Pracownik", "Sprzedaje" };
	private final String ACTION_MENU_CAPTION = "Akcja";
	private final String SHOW_PRIVILIGES_CAPTION = "Pokaz Uprawnienia";
	private final String LOGOUT_CAPTION = "Wyloguj";
	private final String UPDATE_CAPTION = "Zmodyfikuj";
	private final String DELETE_CAPTION = "Usun";
	private final String INSERT_CAPTION = "Dodaj";

	private MenuBar topMenuBar;
	private MenuItem actionMenuItem;
	private MenuItem showPriviligesItem;
	private MenuItem logoutItem;
	private Panel mainPanel;
	private Panel tabsPanel;
	private Panel buttonsPanel;
	private Button updateButton;
	private Button deleteButton;
	private Button insertButton;
	private List<Table> tablesList;
	private TabSheet tabSheet;

	private int selectedTab;
	
	private String username;
	private ArrayList<SimplePermissionEntry> userPermissions;

	public MainView(String username) {
		super();
		
		this.username = username;
		
		//Pobranie uprawnien uzytkownika
		this.userPermissions = new PermissionsDao().getPermissions(this.username);
		
		this.setMargin(true);
		this.mainPanel = new Panel();
		this.setSpacing(true);
		this.tabsPanel = new Panel();
		this.tabsPanel.setStyleName(ChameleonTheme.PANEL_BORDERLESS);
		this.buttonsPanel = new Panel();
		this.buttonsPanel.setStyleName(ChameleonTheme.PANEL_BORDERLESS);
		this.updateButton = new Button(this.UPDATE_CAPTION, this);
		this.insertButton = new Button(this.INSERT_CAPTION, this);
		this.deleteButton = new Button(this.DELETE_CAPTION, new Button.ClickListener() {
		
			/**
			 * 
			 */
			private static final long serialVersionUID = 2722503203034506539L;

			@Override
			public void buttonClick(ClickEvent event) {
				Object itemId = null;
				Table t = tablesList.get(selectedTab);
				Object rowId = t.getValue();
				if(rowId == null) {
					getWindow().showNotification("Nie zaznaczono rekordu!",
							Notification.TYPE_ERROR_MESSAGE);
					return;
				} else if(selectedTab == 6) {
					StringBuilder builder = new StringBuilder(
							t.getContainerProperty(rowId, "Pracownik").getValue().toString());
					builder.append(",");
					builder.append(t.getContainerProperty(rowId, "Sprzedaz").getValue().toString());
					itemId = (Object) builder.toString();
					
				} else if(selectedTab == 3) {
					itemId = t.getContainerProperty(rowId, "Numer").getValue();
				} else
					itemId = t.getContainerProperty(rowId, "ID").getValue();
				switch(selectedTab) {
					case 0:
						new SamochodDao().delete((Integer) itemId);
						break;
					case 1:
						new SprzedazDao().delete((Integer) itemId);
						break;
					case 2:
						new KlientDao().delete((Integer) itemId);
						break;
					case 3:
						new FakturaDao().delete(itemId.toString());
						break;
					case 4:
						new SalonDao().delete((Integer) itemId);
						break;
					case 5:
						new PracownikDao().delete((Integer) itemId);
						break;
					case 6:
						String[] ids = itemId.toString().split(",");
						new SprzedajeDao().delete(Integer.valueOf(ids[0]),
								Integer.valueOf(ids[1]));
						break;
				}
				updateTables();
			}
		});
		HorizontalLayout buttonsLayout = new HorizontalLayout();
		buttonsLayout.setSpacing(true);
		this.buttonsPanel.setContent(buttonsLayout);
		this.buttonsPanel.addComponent(this.insertButton);
		this.buttonsPanel.addComponent(this.updateButton);
		this.buttonsPanel.addComponent(this.deleteButton);
		
		this.selectedTab = 0;

		// gorne menu
		this.topMenuBar = new MenuBar();
		this.actionMenuItem = this.topMenuBar.addItem(this.ACTION_MENU_CAPTION,
				null);
		this.showPriviligesItem = this.actionMenuItem.addItem(
				this.SHOW_PRIVILIGES_CAPTION, this);
		this.logoutItem = this.actionMenuItem
				.addItem(this.LOGOUT_CAPTION, this);

		// taby dolne
		this.tablesList = new ArrayList<Table>();
		VerticalLayout tabsPanelLayout = new VerticalLayout();
		tabsPanelLayout.setSpacing(true);
		this.tabSheet = new TabSheet();
		this.loadTables();
		this.tabsPanel.addComponent(this.tabSheet);

		// dodanie elementow do ramki
		this.addComponent(this.topMenuBar);
		this.addComponent(mainPanel);
		this.mainPanel.addComponent(this.buttonsPanel);
		this.mainPanel.addComponent(this.tabsPanel);
		

	}

	private void loadTables() {
		// TODO: Odwolanie do DAO w celu sciagniecia tabel

		this.tabSheet.addListener(new TabSheet.SelectedTabChangeListener() {

			/**
			 * 
			 */
			private static final long serialVersionUID = 7717751770842865468L;

			@Override
			public void selectedTabChange(SelectedTabChangeEvent event) {
				// TODO Wczytac z bazy dane do wybranej tabeli
				Table selectedTable = (Table) tabSheet.getSelectedTab();
				selectedTab = tablesList.indexOf(selectedTable);

				switch (selectedTab) {
				case 0:
					if(userPermissions.contains(new SimplePermissionEntry("samochod", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifySamochod.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("samochod", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("samochod", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("samochod", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 1:
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaz", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifySprzedaz.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaz", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaz", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaz", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 2:
					if(userPermissions.contains(new SimplePermissionEntry("klient", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifyKlient.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("klient", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("klient", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("klient", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 3:
					if(userPermissions.contains(new SimplePermissionEntry("faktura", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifyFaktura.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("faktura", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("faktura", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("faktura", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 4:
					if(userPermissions.contains(new SimplePermissionEntry("salon", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifySalon.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("salon", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("salon", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("salon", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 5:
					if(userPermissions.contains(new SimplePermissionEntry("pracownik", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifyPracownik.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("pracownik", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("pracownik", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("pracownik", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				case 6:
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaje", "select"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						ModifySprzedaje.fillTable(selectedTable);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaje", "insert"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						insertButton.setEnabled(true);
					else
						insertButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaje", "update"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						updateButton.setEnabled(true);
					else
						updateButton.setEnabled(false);
					if(userPermissions.contains(new SimplePermissionEntry("sprzedaje", "delete"))
							|| (userPermissions.size() > 0 && userPermissions.get(0).getObiekt().equals("admin")))
						deleteButton.setEnabled(true);
					else
						deleteButton.setEnabled(false);
					break;
				}

				selectedTable.setSelectable(true);
				selectedTable.setStyleName(ChameleonTheme.TABLE_STRIPED);
			}
		});

		for (int i = 0; i < NAMES.length; i++) {
			Table table = new Table();
			this.tablesList.add(table);
			this.tabSheet.addTab(table, NAMES[i]);
		}
	}

	@Override
	public void menuSelected(MenuItem selectedItem) {
		if (selectedItem == this.showPriviligesItem) {
			//TODO rozmiar okienka
			Window modalWindow;
			modalWindow = new Window();
			modalWindow.setResizable(true);
			BskGuiApplication currentApplication = (BskGuiApplication) this
					.getApplication();
			modalWindow.setContent(new EditPrivilegesView(currentApplication
					.getCurrentUserName()));
			modalWindow.setModal(true);
			modalWindow.setWidth("950px");
			modalWindow.addListener(new Window.CloseListener() {
				@Override
				public void windowClose(CloseEvent e) {
					// TODO Auto-generated method stub
					userPermissions = new PermissionsDao().getPermissions(username);
					tabSheet.removeAllComponents();
					tablesList.clear();
					loadTables();
				}
			});
			this.getWindow().addWindow(modalWindow);
		} else if (selectedItem == this.logoutItem) {
			BskGuiApplication currentApplication = (BskGuiApplication) this
					.getApplication();
			currentApplication.setCurrentUserName(null);
			this.getWindow().setContent(new LoginView());
		}
	}

	@Override
	public void buttonClick(ClickEvent event) {
		// TODO: dodac obsluge kliknietego row-a, dopracowac, usunac duplikujacy
		// sie kod, ustawic rozmiar okienek

		Window modalWindow;
		modalWindow = new Window();
		modalWindow.setResizable(true);
		Object itemId = null;
		Table t = tablesList.get(selectedTab);
		if(event.getComponent() == this.updateButton) {
			Object rowId = t.getValue();
			if(rowId == null) {
				this.getWindow().showNotification("Nie zaznaczono rekordu!",
						Notification.TYPE_ERROR_MESSAGE);
				return;
			}
			else if(selectedTab == 6) {
				StringBuilder builder = new StringBuilder(
						t.getContainerProperty(rowId, "Pracownik").getValue().toString());
				builder.append(",");
				builder.append(t.getContainerProperty(rowId, "Sprzedaz").getValue().toString());
				itemId = (Object) builder.toString();
				
			} else if(selectedTab == 3) {
				itemId = t.getContainerProperty(rowId, "Numer").getValue();
			} else
				itemId = t.getContainerProperty(rowId, "ID").getValue();
		}

		if (event.getComponent() == this.updateButton) {
			modalWindow = new Window("Modyfikacja");
			ConfigureModalWindow(false, itemId, modalWindow);
		} else if (event.getComponent() == this.insertButton) {
			modalWindow = new Window("Wstaw");
			ConfigureModalWindow(true, itemId, modalWindow);
		}

		modalWindow.setModal(true);
		modalWindow.addListener(new Window.CloseListener() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = 3686975892971236174L;

			@Override
			public void windowClose(CloseEvent e) {
				// TODO Auto-generated method stub
				updateTables();
			}
		});
		this.getWindow().addWindow(modalWindow);
	}

	private void ConfigureModalWindow(boolean isInsert, Object id,
			Window modalWindow) {
		ModifyLayout modifyLayout = null;
		switch (selectedTab) {
			case 0:
				modifyLayout = new ModifySamochod(isInsert, (Integer) id, modalWindow);
				break;
			case 1:
				modifyLayout = new ModifySprzedaz(isInsert, (Integer) id, modalWindow);
				break;
			case 2:
				modifyLayout = new ModifyKlient(isInsert, (Integer) id, modalWindow);
				break;
			case 3:
				modifyLayout = new ModifyFaktura(isInsert, id.toString(), modalWindow);
				break;
			case 4:
				modifyLayout = new ModifySalon(isInsert, (Integer) id, modalWindow);
				break;
			case 5:
				modifyLayout = new ModifyPracownik(isInsert, (Integer)id, modalWindow);
				break;
			case 6:
				modifyLayout = new ModifySprzedaje(isInsert, (String) id, modalWindow);
				break;
		}

		modalWindow.setContent(modifyLayout);
		modalWindow.setWidth(modifyLayout.getWinWidth());
		modalWindow.setHeight(modifyLayout.getWinHeight());
	}
	
	private void updateTables() {
		switch (selectedTab) {
			case 0:
				ModifySamochod.refresh(tablesList.get(selectedTab));
				break;
			case 1:
				ModifySprzedaz.refresh(tablesList.get(selectedTab));
				break;
			case 2:
				ModifyKlient.refresh(tablesList.get(selectedTab));
				break;
			case 3:
				ModifyFaktura.refresh(tablesList.get(selectedTab));
				break;
			case 4:
				ModifySalon.refresh(tablesList.get(selectedTab));
				break;
			case 5:
				ModifyPracownik.refresh(tablesList.get(selectedTab));
				break;
			case 6:
				ModifySprzedaje.refresh(tablesList.get(selectedTab));
				break;
		}
	}

	
}
